package com.tarena.lbs.marketing.repository.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.marketing.mapper.CouponMapper;
import com.tarena.lbs.marketing.repository.CouponRepository;
import com.tarena.lbs.pojo.marketing.bo.CouponBO;
import com.tarena.lbs.pojo.marketing.dos.CouponDO;
import com.tarena.lbs.pojo.marketing.query.CouponQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class CouponRepositoryImpl implements CouponRepository {
    @Autowired
    private CouponMapper couponMapper;

    public BasePageList<CouponBO> getCouponPage(CouponQuery query, Integer businessId) {
        //1. 准备一个DO
        CouponDO couponDO=new CouponDO();
        //2. 转化一下
        if (query!=null){
            BeanUtils.copyProperties(query,couponDO);
        }
        couponDO.setBusinessId(businessId);
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        List<CouponDO> dos= couponMapper.selectCouponPage(couponDO);
        PageInfo<CouponDO> infoDos=new PageInfo<>(dos);
        long total = infoDos.getTotal();
        BasePageList<CouponBO> pageBos=null;
        if (total>0){
            //查询dos有值 转化成BO 给业务使用
            List<CouponBO> bos=infoDos.getList().stream().map(cDO->{
                CouponBO couponBO=new CouponBO();
                BeanUtils.copyProperties(cDO,couponBO);
                return couponBO;
            }).collect(Collectors.toList());
            pageBos=new BasePageList<>(bos,total);
            return pageBos;
        }
        pageBos=new BasePageList<>(null,total);
        return pageBos;
    }

    @Override
    public Integer saveCoupon(CouponBO bo) {
        //转化成do
        CouponDO cDO=new CouponDO();
        BeanUtils.copyProperties(bo,cDO);
        couponMapper.insert(cDO);
        return cDO.getId();
    }

    @Override
    public CouponBO getCouponById(Integer id) {
        CouponDO cDo=couponMapper.selectCouponById(id);
        CouponBO bo=null;
        if (cDo!=null){
            bo=new CouponBO();
            BeanUtils.copyProperties(cDo,bo);
        }
        return bo;
    }
}
